package cn.honqun.tinycms.common.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页对象.包含数据及分页信息.继承自PageDTO,增加了单字段排序功能，并为客户端
 * 分页工具条提供数据
 *
 * @author Sam
 */
@Setter
@Getter
public class
Page<T> extends PageDTO<T> {
    private static final long serialVersionUID = 1L;
    private static final int DEFAULT_STEPS = 10;

    private String orderBy;

    private String orderDir;

    public Page() {
    }

    public Page(long current, long size) {
        this(current, size, 0);
    }

    public Page(long current, long size, long total) {
        super(current, size, total, true);
    }

    public Page(long current, long size, boolean searchCount) {
        super(current, size, 0, searchCount);
    }

    public Page(long current, long size, long total, boolean searchCount) {
        super(current, size, total, searchCount);
    }

    @SuppressWarnings("rawtypes")
    public Page(IPage iPage) {
        super(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.searchCount());
    }

    public int getOffset() {
        return (int) offset();
    }

    /**
     * 用于实现Google风格的分页
     */
    public Integer[] getSteps() {
        int startPage = calcStartPage();
        int stepSize = calcStepPageSize();
        List<Integer> steps = new ArrayList<>();
        for (int i = startPage; i < startPage + stepSize; i++) {
            steps.add(i);
        }
        return steps.toArray(new Integer[]{});
    }

    /**
     * calculate fist page No of fast step.
     */
    private int calcStartPage() {
        if (getCurrent() < (DEFAULT_STEPS / 2) || (getCurrent() - (DEFAULT_STEPS / 2)) < 1) {
            return 1;
        } else {
            return (int) getCurrent() - (DEFAULT_STEPS / 2);
        }
    }

    private int calcStepPageSize() {
        if ((calcStartPage() + DEFAULT_STEPS) > getPages()) {
            return (int) getPages() - calcStartPage() + 1;
        } else {
            return DEFAULT_STEPS;
        }
    }
}
